package synchronize.synchronize006;

/**
 * 使用synchronized代码块加锁，比较灵活
 */
public class ObjectLock {

    /**
     * 锁对象，打印一个编辑，休眠两秒
     */
    public void method1() {
        //this指的是ObjectLock的实例对象
        synchronized (this) {
            try {
                System.out.println("do method1..");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 锁类，打印个标记，睡眠两秒
     */
    public void method2() {
        //锁类
        synchronized (ObjectLock.class) {
            try {
                System.out.println("do method2..");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public Object lock = new Object();

    /**
     * 锁传入的任何对象
     */
    public void method3() {
        synchronized (lock) {
            try {
                System.out.println("do method3..");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final ObjectLock objectLock = new ObjectLock();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                objectLock.method1();
            }
        });
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                objectLock.method2();
            }
        });
        t2.start();
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                objectLock.method3();
            }
        });
        t3.start();
    }

}
